﻿using System.Collections.Generic;
using System.Xml;
using Microsoft.Xrm.Sdk;
using SolutionExtender.AppCode;
using SolutionExtender.Controls;
using SolutionExtender.Interfaces;

namespace McTools.SolutionExtender.UserQueryToSystemPlugin
{
    public class UserQueryToSystemConnector : IConnector
    {
        #region Variables

        /// <summary>
        /// IOrganization service to access CRM 2011 data
        /// </summary>
        private readonly IOrganizationService _service;

        #endregion Variables

        #region Constructor

        /// <summary>
        /// Initializes a new instance of class UserQueryToSystemConnector
        /// </summary>
        /// <param name="service">IOrganization service to access CRM 2011 data</param>
        public UserQueryToSystemConnector(IOrganizationService service)
        {
            _service = service;
        }

        #endregion Constructor

        #region Properties

        public string ObjectName
        {
            get { return "Saved view (conversion to system view)"; }
        }

        public string Description
        {
            get { return ""; }
        }

        #endregion Properties

        #region Methods

        public List<ImportResult> Import(XmlNode data)
        {
            var queryObject =
                (UserQuery)XmlSerializerHelper.Deserialize(data.OuterXml, typeof(UserQuery));

            var query = new Entity("savedquery");

            query["advancedgroupby"] = queryObject.AdvancedGroupBy;
            query["columnsetxml"] = queryObject.ColumnSetXml;
            query["conditionalformatting"] = queryObject.ConditionalFormatting;
            query["description"] = queryObject.Description;
            query["fetchxml"] = queryObject.FetchXml;
            query["layoutxml"] = queryObject.LayoutXml;
            query["name"] = queryObject.Name;
            query["querytype"] = queryObject.QueryType;
            query["returnedtypecode"] = queryObject.ReturnedTypeCode;

            _service.Create(query);

            return null;
        }

        public IExportControl GetExportControl(IOrganizationService service)
        {
            return new UserQueryToSystemExportControl(_service);
        }

        public string GetRecordName(XmlNode node)
        {
            return node.SelectSingleNode("Name").InnerText;
        }

        #endregion Methods
    }
}
